package com.user.command;

import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.ibatis.session.SqlSession;

import com.user.applaction.SessionManager;
import com.user.applaction.UserApp;
import com.user.mapping.UserMapping;
import com.user.tool.Tool;

public class ImprovementCommand implements Command {

	@Override
	public void excute() {
		String gender = "";
		SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd");
		SqlSession session = SessionManager.getInstance().getSession();
		UserMapping mapper = session.getMapper(UserMapping.class);
		
		//判断姓名
		UserApp.getUser().setUserName(Tool.askUserInputNotNull("修改您的姓名/昵称"));

		// 判断日期输入是否正确
		while (true) {
			try {
				UserApp.getUser().setUserBirth(sdf.parse(Tool.askUserInputNotNull("修改您的生日 yyyy-MM-dd")));
				break;
			} catch (Exception e) {
				Tool.printMsg("日期输入错误,重新输入");
			}
		}

		// 判断性别
		while (true) {
			String genderStr = Tool.askUserInputNotNull("修改您的性别 1代表男，2代表女");
			if ("1".equals(genderStr) ) {
				gender = "Male";
				break;
			} else if ("2".equals(genderStr)) {
				gender = "Female";
				break;
			} else {
				Tool.printMsg("不正确输入，重新输入您的性别");
			}
		}
		UserApp.getUser().setUserGender(gender);
		
		// 判断手机号码
		String regEx = "^1[3|4|5|7|8][0-9]{9}$";
		Pattern pattern = Pattern.compile(regEx);
		String phoneNumber;
		while (true) {
			phoneNumber = Tool.askUserInputNotNull("修改您的11位手机号码");
			Matcher matcher = pattern.matcher(phoneNumber);
			if (matcher.matches()) {
				break;
			}else {
				Tool.printMsg("无效的手机号码");
			}
		}
		UserApp.getUser().setUserPhone(phoneNumber);
		
		// 判断Email
		regEx = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";
		pattern = Pattern.compile(regEx);
		String email;
		while (true) {
			email = Tool.askUserInputNotNull("修改您的邮箱");
			Matcher matcher = pattern.matcher(email);
			if (matcher.matches()) {
				break;
			}else {
				Tool.printMsg("无效的邮箱");
			}
		}
		UserApp.getUser().setUserEmail(email);
		System.out.println(UserApp.getUser().toString());
		//
		int rows = mapper.updateUser(UserApp.getUser());
		if(rows > 0) {
			Tool.printMsg("修改成功！");
		}else {
			Tool.printMsg("因为一些错误，未成功！");
		}
		
		//
		session.commit();
		session.close();
	}

}
